package br.ufpb.di.ppgi.apresentacao.controllers;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.ValidationMessage;
import br.com.caelum.vraptor.view.Results;
import br.com.simtecnologia.access.controll.DefaultLoginSession;
import br.com.simtecnologia.access.controll.LoginFlow;
import br.com.simtecnologia.access.controll.annotation.LoginLogic;
import br.ufpb.di.ppgi.negocio.ServiceLocator;
import br.ufpb.di.ppgi.negocio.iservicos.ILoginService;
import br.ufpb.di.ppgi.negocio.modelo.usuario.Usuario;
import br.ufpb.di.ppgi.negocio.servicos.login.Credencial;
import br.ufpb.di.ppgi.persistencia.transaction.TransactionScoped;

@Path("/")
@Resource
public class RootController extends AbstractController{

	
	
	private final ILoginService iLoginService;
	private final LoginFlow loginFlow;

	public RootController(Result result, Validator validator,
			ServiceLocator services, LoginFlow loginFlow, ILoginService iLoginService) {
		super(result, validator, services);
		this.iLoginService = services.forLogin();
		this.loginFlow = loginFlow;
	}

	@Get
	@Path("")
	@LoginLogic(defaultFor=DefaultLoginSession.class)
	public void index() {
	}

	@Post
	@Path("login")
	public void login(Credencial credencial,Long loginFlowId) { //NxWfKBv3uQ
		if (credencial != null && iLoginService.login(credencial)) {
			if (loginFlowId != null) {
				if (loginFlow.retrieveFlowBeforeLogin(loginFlowId)) 
					return;
				else if (loginFlow.retrieveFlowBeforeLogin())
					return;
			} else
			result.redirectTo(RootRestrictController.class).index();
		} else {
			result.include("loginFlowId", loginFlowId);
			
			validator.add(new ValidationMessage("Login Invalido", "login"));
			validator.onErrorUse(Results.logic()).redirectTo(RootController.class).index();
		}
	}
	

	@Path("logout")
	public void logout() {
		services.forLogin().logout();
		result.redirectTo(this).index();
	}
	
	@Path("about")
	public void about() {
	}
	
	@Get
	@Path("esqueciMinhaSenha")
	public void esqueciMinhaSenha() {
		
	}
	
	@Post
	@Path("esqueciMinhaSenha")
	@TransactionScoped
	public void esqueciMinhaSenha(String email) {
		Usuario usuario = services.forUsuario().findByEmail(email);
		if (usuario != null) {
			services.forUsuario().resetarSenhaEnviarEmail(usuario);
			validator.add(new ValidationMessage("Um email foi enviado contendo sua nova senha.", "error"));
		} else
			validator.add(new ValidationMessage("Email não cadastrado.", "error"));
		
		validator.onErrorUse(Results.logic()).redirectTo(getClass()).esqueciMinhaSenha();
	}
}